package com.example.activelifecycletest.network.json;

import android.os.Bundle;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.List;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * gson
 * @author zhangding
 * @date 2022年5月8日21:13:22
 */
public class GsonActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sendRequestWithOkhttp();
    }

    /**
     * 发送http请求
     */
    private void sendRequestWithOkhttp(){
        new Thread(() -> {
            try {

                OkHttpClient client = new OkHttpClient();
                /*
                  模拟器会将127.0.0.1识别为模拟器本身
                  因此需要使用192.168.10.7局域网ip或者10.0.2.2去访问模拟器本身的主机
                 */
                Request request = new Request.Builder()
                        .url("http://192.168.10.7/android_data.json")
                        .build();
                Response response = client.newCall(request).execute();
                String responseData = response.body() == null?"":response.body().string();
                parseJSONWithGson(responseData);
            }catch (Exception e){
                e.printStackTrace();
            }
        }).start();

    }

    /**
     * 返回json串解析
     * @param jsonData json数据
     */
    private void parseJSONWithGson(String jsonData){
        try {
            Gson gson = new Gson();
            List<GsonPOJO> GsonPOJOList = gson.fromJson(jsonData,new TypeToken<List<GsonPOJO>>(){}.getType());
            for (GsonPOJO gsonPOJO :GsonPOJOList){
                Log.d("zhang","id :" + gsonPOJO.getId());
                Log.d("zhang","name :" + gsonPOJO.getName());
                Log.d("zhang","version :" + gsonPOJO.getVersion());

            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
